package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page = roleDao.findPage(queryString);
        long total = page.getTotal();
        List<Role> result = page.getResult();
        return new PageResult(total,result);
    }

    @Override
    public List<Permission> findAllPermission() {
        return roleDao.findAllPermission();
    }

    @Override
    public void addRole(Integer[] permissionsIds, Role role) {
        roleDao.addRole(role);
        this.addRoleAndPermissionTableMethod(role.getId(),permissionsIds);
    }

    @Override
    public Role findOneRole(Integer roleId) {
        return roleDao.findOneRole(roleId);
    }

    @Override
    public List<Integer> findAllPermissionByRoleId(Integer roleId) {
        return roleDao.findAllPermissionByRoleId(roleId);
    }

    @Override
    public void editRole(Integer[] permissionsIds, Role role) {
        roleDao.editRole(role);
        roleDao.clearMiddleTable(role.getId());
        this.addRoleAndPermissionTableMethod(role.getId(), permissionsIds);
    }

    @Override
    public void deleteRoleById(Integer roleId) {
        roleDao.clearMiddleTable(roleId);
        roleDao.deleteRole(roleId);
    }

    public void addRoleAndPermissionTableMethod(Integer roleId, Integer[] permissionsIds)    {
        if (permissionsIds != null && permissionsIds.length > 0) {
            for (Integer permissionsId : permissionsIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("roleId",roleId);
                map.put("permissionsId", permissionsId);
                roleDao.addRoleAndPermissionTable(map);
            }
        }
    }

}
